package test.src.awt_swing;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageIO {
    Frame frame = new Frame("图片浏览器");

    MenuBar menuBar = new MenuBar();
    Menu fileMenu = new Menu("文件");
    MenuItem open = new MenuItem("打开图片");
    MenuItem save = new MenuItem("保存图片");

    BufferedImage image;

    private class MyCanvas extends Canvas {
        @Override
        public void paint(Graphics g) {
            g.drawImage(image, 0, 0, null);
        }
    }

    private void init() {
        //组装视图
        MyCanvas drawArea = new MyCanvas();

        open.addActionListener(e -> {
            FileDialog fileDialog = new FileDialog(frame, "打开图片", FileDialog.LOAD);
            fileDialog.setVisible(true);

            //获取文件路径及文件名
            String dir = fileDialog.getDirectory();
            String fileName = fileDialog.getFile();

            try {
                    image = javax.imageio.ImageIO.read(new File(dir, fileName));
                    System.out.println(dir);
                    System.out.println(fileName);
                    drawArea.repaint();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        });

        save.addActionListener(e -> {
            FileDialog fileDialog = new FileDialog(frame, "保存图片", FileDialog.SAVE);
            fileDialog.setVisible(true);

            //获取文件路径及文件名
            String dir = fileDialog.getDirectory();
            String fileName = fileDialog.getFile();

            try {
                javax.imageio.ImageIO.write(image,"JPEG", new File(dir, fileName));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });

        fileMenu.add(open);
        fileMenu.add(save);
        menuBar.add(fileMenu);

        frame.setMenuBar(menuBar);
        frame.add(drawArea);

        frame.setBounds(200, 200, 740, 508);
        frame.setPreferredSize(new Dimension(740, 508));
        frame.pack();
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        new ImageIO().init();
    }
}
